package com.example.business.service.impl;

import com.example.business.dao.NewsDetailDTO;
import com.example.business.dao.dto.NewsDTO;
import com.example.business.dao.entity.News;
import com.example.business.dao.entity.NewsDetails;
import com.example.business.dao.mapper.NewsDetailsMapper;
import com.example.business.dao.mapper.NewsMapper;
import com.example.business.service.NewsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class NewsServiceImpl implements NewsService {
    private final NewsMapper newsMapper;
    private final NewsDetailsMapper newsDetailsMapper;

    @Override
    public List<NewsDTO> getNews() {
        try {
            List<News> newsList = newsMapper.selectLatestNews(2);
            List<NewsDTO> result = new ArrayList<>();

            for (News news : newsList) {
                NewsDetails details = newsDetailsMapper.selectByNewsId(news.getId());
                String summary = details != null ? details.getContent() : "";
                if (summary.length() > 150) {
                    summary = summary.substring(0, 150) + "...";
                }

                NewsDTO dto = new NewsDTO();
                dto.setId(news.getId()); // 新闻ID
                dto.setTitle(news.getTitle());
                dto.setSummary(summary);
                result.add(dto);
            }
            return result;
        } catch (Exception e) {
            log.error("获取推荐新闻失败", e);
            throw new RuntimeException("获取推荐新闻失败");
        }

    }

    @Override
    public NewsDetailDTO getNewsDetails(Long newsId) {
        try {
            NewsDetails details = newsDetailsMapper.selectByNewsId(newsId);
            if (details == null) {
                throw new RuntimeException("获取新闻详情失败");
            }

            NewsDetailDTO dto = new NewsDetailDTO();
            dto.setContent(details.getContent());
            return dto;
        } catch (Exception e) {
            log.error("获取新闻详情失败", e);
            throw new RuntimeException("获取新闻详情失败");
        }
    }
}
